//
//  ISSafetyGuideViewController.m
//  iPhoneSafety
//
//  Created by dl on 2019/1/9.
//  Copyright © 2019 com.li.ding. All rights reserved.
//

#import "ISSafetyGuideViewController.h"
#import "UIControl+BlocksKit.h"
#import <AVFoundation/AVFoundation.h>
#import "ISSafetyAlarmMailManager.h"
#import <UserNotifications/UserNotifications.h>
#import <CoreTelephony/CTCellularData.h>

@interface ISSafetyGuideAuthItemView : UIView
@property (nonatomic, strong) UIImageView *iconImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *subTitleLabel;
@property (nonatomic, strong) UIButton *btn;
@end
@implementation ISSafetyGuideAuthItemView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.iconImageView];
        [self addSubview:self.titleLabel];
        [self addSubview:self.subTitleLabel];
        [self addSubview:self.btn];
        [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@14.f);
            make.centerY.equalTo(self);
            make.size.mas_equalTo(CGSizeMake(60.f, 60.f));
        }];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.iconImageView.mas_right).offset(15.f);
            make.top.equalTo(self.iconImageView).offset(8.f);
            make.height.equalTo(@20.f);
        }];
        [self.subTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.titleLabel);
            make.top.equalTo(self.titleLabel.mas_bottom).offset(10.f);
            make.height.equalTo(@16.f);
        }];
        [self.btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(@-14.f);
            make.centerY.equalTo(self);
            make.size.mas_equalTo(CGSizeMake(64.f, 32.f));
        }];
    }
    return self;
}
#pragma mark - getters
NWLazyPropertyWithInit(UIImageView, iconImageView, {
    _iconImageView.contentMode = UIViewContentModeScaleAspectFit;
})
NWLazyPropertyWithInit(UILabel, titleLabel, {
    _titleLabel.font = [UIFont nw_systemFontOfSize:16 weight:NWFontWeightMedium];
    _titleLabel.textColor = [UIColor whiteColor];
})
NWLazyPropertyWithInit(UILabel, subTitleLabel, {
    _subTitleLabel.font = [UIFont systemFontOfSize:13];
    _subTitleLabel.textColor = [UIColor nw_colorWithHex:0xFFFFFF alpha:0.4f];
})
NWLazyPropertyWithInit(UIButton, btn, {
    _btn.layer.cornerRadius = 16.f;
    _btn.layer.borderColor = [UIColor whiteColor].CGColor;
    _btn.layer.borderWidth = 2.f;
    _btn.titleLabel.font = [UIFont nw_systemFontOfSize:15 weight:NWFontWeightMedium];
    [_btn setTitle:@"开启" forState:UIControlStateNormal];
    [_btn setTitle:@"已开启" forState:UIControlStateDisabled];
})
@end

@interface ISSafetyGuideViewController () <UIScrollViewDelegate>
@property (nonatomic, strong) UIImageView *firstBgImageView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) UIScrollView *loopScrollView;
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) UILabel *loopTitleLabel;
@property (nonatomic, strong) UILabel *loopSubTitleLabel;
@property (nonatomic, strong) NSArray<UIImageView *> *loopImageViews;
@property (nonatomic, strong) UIButton *firstBtn;

@property (nonatomic, strong) UIImageView *secondBgImageView;
@property (nonatomic, strong) UILabel *secondTitleLabel;
@property (nonatomic, strong) UILabel *secondSubTitleLabel;
@property (nonatomic, strong) NSArray<ISSafetyGuideAuthItemView *> *authItemViews;
@property (nonatomic, strong) UIButton *secondBtn;
@property (nonatomic, strong) UIButton *secondSkipBtn;

@property (nonatomic, assign) NSInteger showingGuideIndex;
@end

@implementation ISSafetyGuideViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.fd_prefersNavigationBarHidden = YES;
    self.fd_interactivePopDisabled = YES;
    self.view.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:self.firstBgImageView];
    [self.firstBgImageView addSubview:self.loopTitleLabel];
    [self.firstBgImageView addSubview:self.loopSubTitleLabel];
    [self.firstBgImageView addSubview:self.loopScrollView];
    [self.firstBgImageView addSubview:self.pageControl];
    [self.loopImageViews enumerateObjectsUsingBlock:^(UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.loopScrollView addSubview:obj];
    }];
    [self.firstBgImageView addSubview:self.firstBtn];
    
    [self.view addSubview:self.secondBgImageView];
    [self.secondBgImageView addSubview:self.secondTitleLabel];
    [self.secondBgImageView addSubview:self.secondSubTitleLabel];
    [self.authItemViews enumerateObjectsUsingBlock:^(ISSafetyGuideAuthItemView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.secondBgImageView addSubview:obj];
        
        @weakify(self)
        [obj.btn bk_addEventHandler:^(id sender) {
            @strongify(self)
            if (idx == 0) {
                [self authLocalNoti];
            } else if(idx == 1) {
                [self authNetwork];
            } else if(idx == 2) {
                [self authLocation];
            }
        } forControlEvents:UIControlEventTouchUpInside];
    }];
    [self.secondBgImageView addSubview:self.secondBtn];
    [self.secondBgImageView addSubview:self.secondSkipBtn];
    
    self.pageControl.numberOfPages = self.loopImageViews.count;
    
    [@[
       @{@"icon": @"img_permission_push", @"title": @"允许通知", @"sub_title": @"用于即使推送安全通知"},
       @{@"icon": @"img_permission_network", @"title": @"获取联网权限", @"sub_title": @"建议开启4G+Wi-Fi"},
       @{@"icon": @"img_permission_push", @"title": @"获取地理位置", @"sub_title": @"用于防盗抓拍，定位嫌疑人位置"}
       ] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * _Nonnull stop) {
           self.authItemViews[idx].iconImageView.image = [UIImage imageNamed:obj[@"icon"]];
           self.authItemViews[idx].titleLabel.text = obj[@"title"];
           self.authItemViews[idx].subTitleLabel.text = obj[@"sub_title"];
       }];
    
    [self startTimer];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:kISSafetyAlarmAuthLocationNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        if ([note.object boolValue]) {
            self.authItemViews.lastObject.btn.enabled = NO;
            self.authItemViews.lastObject.btn.alpha = 0.4f;
        } else {
            [self gotoSetting];
        }
    }];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self stopTimer];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.firstBgImageView.frame = CGRectMake(-self.showingGuideIndex * self.view.width, 0, self.view.width, self.view.height);
    self.loopTitleLabel.frame = CGRectMake(0.f, 80.f, self.view.width, 30.f);
    self.loopSubTitleLabel.frame = CGRectMake(self.view.width * 0.25f, 125.f, self.view.width * 0.5f, 40.f);
    self.loopScrollView.frame = CGRectMake(0.f, self.view.height * 170.f / 667.f, self.view.width, 300.f * self.view.height / 667.f);
    self.pageControl.frame = CGRectMake((self.view.width - 100.f) / 2.f, self.loopScrollView.bottom + 10.f, 100.f, 10);
    [self.loopImageViews enumerateObjectsUsingBlock:^(UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CGFloat height = self.loopScrollView.width / 375.f * 300.f;
        obj.frame = CGRectMake(idx * self.loopScrollView.width, self.loopScrollView.height - height, self.loopScrollView.width, height);
    }];
    self.loopScrollView.contentSize = CGSizeMake(self.loopScrollView.width * self.loopImageViews.count, self.loopScrollView.height);
    self.firstBtn.frame = CGRectMake(14.f, self.pageControl.bottom + 55.f, self.view.width - 28.f, 60.f);
    
    self.secondBgImageView.frame = CGRectMake((1 - self.showingGuideIndex) * self.view.width, 0.f, self.view.width, self.view.height);
    self.secondTitleLabel.frame = CGRectMake(0.f, 80.f, self.view.width, 30.f);
    self.secondSubTitleLabel.frame = CGRectMake(self.view.width * 0.25f, 125.f, self.view.width * 0.5f, 40.f);
    CGFloat offsetY = (self.view.height - 300.f) / 2.f;
    [self.authItemViews enumerateObjectsUsingBlock:^(ISSafetyGuideAuthItemView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.frame = CGRectMake(0.f, offsetY + idx * 100.f, self.view.width, 100.f);
    }];
    self.secondBtn.frame = CGRectMake(14.f, self.authItemViews.lastObject.bottom + 70.f, self.view.width - 28.f, 60.f);
    self.secondSkipBtn.frame = CGRectMake(14.f, self.secondBtn.bottom, self.secondBtn.width, 52.f);
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat showIdx = roundf(MIN(self.loopImageViews.count - 1, MAX(0, scrollView.contentOffset.x / scrollView.width)));
    self.pageControl.currentPage = showIdx;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self stopTimer];
}

- (void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self startTimer];
}

#pragma mark - timer
- (void) startTimer {
    [self stopTimer];
    @weakify(self)
    self.timer = [NSTimer bk_timerWithTimeInterval:3.f block:^(NSTimer *timer) {
        @strongify(self)
        CGFloat nextIdx = self.pageControl.numberOfPages > self.pageControl.currentPage + 1 ? self.pageControl.currentPage + 1 : 0;
        [self.loopScrollView setContentOffset:CGPointMake(nextIdx * self.loopScrollView.width, 0) animated:YES];
    } repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void) stopTimer {
    if ([self.timer isValid]) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void) authAll {
    [self authLocation];
    [self authNetwork];
    [self authLocalNoti];
}

- (void) authLocation {
    [[ISSafetyAlarmMailManager sharedInstance] requestLocationAuthorization];
}

- (void) authNetwork {
    CTCellularData *cellularData = [[CTCellularData alloc] init];
    cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state) {
        switch (state) {
            case kCTCellularDataRestricted:
                [self gotoSetting];
                break;
            case kCTCellularDataNotRestricted:
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.authItemViews[1].btn.enabled = NO;
                    self.authItemViews[1].btn.alpha = 0.4f;
                });
            }
                break;
            case kCTCellularDataRestrictedStateUnknown:
                [self gotoSetting];
                break;
                
            default:
                break;
        }
    };
}

- (void) authLocalNoti {
    if (@available(iOS 10.0, *)) {
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (granted) {
                    self.authItemViews.firstObject.btn.enabled = NO;
                    self.authItemViews.firstObject.btn.alpha = 0.4f;
                } else {
                    [self gotoSetting];
                }
            });
        }];
    } else {
        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
}

- (void) gotoSetting {
    if (self.presentingViewController) {
        return ;
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"去设置权限" message:@"去设置页面设置相关权限" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - getters
NWLazyPropertyWithInit(UIImageView, firstBgImageView, {
    _firstBgImageView.image = [UIImage imageNamed:@"img_guide_01_bg"];
    _firstBgImageView.contentMode = UIViewContentModeScaleToFill;
    _firstBgImageView.userInteractionEnabled = YES;
})
NWLazyPropertyWithInit(UIPageControl, pageControl, {
    _pageControl.pageIndicatorTintColor = [UIColor nw_colorWithHex:0xFFFFFF alpha:0.4f];
    _pageControl.currentPageIndicatorTintColor = [UIColor nw_colorWithHex:0xFFFFFF];
})
NWLazyPropertyWithInit(UIScrollView, loopScrollView, {
    _loopScrollView.pagingEnabled = YES;
    _loopScrollView.showsHorizontalScrollIndicator = NO;
    _loopScrollView.delegate = self;
})
NWLazyPropertyWithInit(UILabel, loopTitleLabel, {
    _loopTitleLabel.text = @"多个场景下的防盗模式";
    _loopTitleLabel.font = [UIFont nw_systemFontOfSize:24 weight:NWFontWeightMedium];
    _loopTitleLabel.textColor = [UIColor whiteColor];
    _loopTitleLabel.textAlignment = NSTextAlignmentCenter;
})
NWLazyPropertyWithInit(UILabel, loopSubTitleLabel, {
    _loopSubTitleLabel.text = @"一键轻松开启，可以并行联防，保护你的手机安全";
    _loopSubTitleLabel.font = [UIFont systemFontOfSize:13];
    _loopSubTitleLabel.textColor = [UIColor nw_colorWithHex:0xffffff alpha:.6f];
    _loopSubTitleLabel.textAlignment = NSTextAlignmentCenter;
    _loopSubTitleLabel.numberOfLines = 0.f;
})
- (NSArray<UIImageView *> *)loopImageViews {
    if (!_loopImageViews) {
        _loopImageViews = [@[@{@"title": @"口袋防盗", @"img": @"img_detail_pocket_banner"},
                             @{@"title": @"桌面防盗", @"img": @"img_detail_desktop_banner"},
                             @{@"title": @"充电防盗", @"img": @"img_detail_charge_banner"},
                             @{@"title": @"飞行防盗", @"img": @"img_detail_airplane_banner"},
                             @{@"title": @"听歌防盗", @"img": @"img_detail_earphone_banner"}] bk_map:^id(id obj) {
                                 UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:obj[@"img"]]];
                                 UILabel *title = [[UILabel alloc] init];
                                 title.text = obj[@"title"];
                                 title.textColor = [UIColor whiteColor];
                                 title.font = [UIFont nw_systemFontOfSize:15 weight:NWFontWeightMedium];
                                 title.textAlignment = NSTextAlignmentCenter;
                                 title.layer.cornerRadius = 4.f;
                                 title.layer.borderColor = [UIColor nw_colorWithHex:0xFFFFFF alpha:0.4f].CGColor;
                                 title.layer.borderWidth = 0.5f;
                                 [imgView addSubview:title];
                                 [title mas_makeConstraints:^(MASConstraintMaker *make) {
                                     make.bottom.centerX.equalTo(imgView);
                                     make.size.mas_equalTo(CGSizeMake(80.f, 30.f));
                                 }];
                                 return imgView;
        }];
    }
    return _loopImageViews;
}
NWLazyPropertyWithInit(UIButton, firstBtn, {
    _firstBtn.backgroundColor = [UIColor nw_colorWithHex:0x0078FF];
    [_firstBtn setTitle:@"了解了" forState:UIControlStateNormal];
    _firstBtn.layer.cornerRadius = 6.f;
    _firstBtn.clipsToBounds = YES;
    @weakify(self)
    [_firstBtn bk_addEventHandler:^(id sender) {
        @strongify(self)
        [UIView animateWithDuration:0.3 animations:^{
            self.showingGuideIndex = 1;
            [self.view setNeedsLayout];
            [self.view layoutIfNeeded];
        }];
    } forControlEvents:UIControlEventTouchUpInside];
})


#pragma mark - second
NWLazyPropertyWithInit(UIImageView, secondBgImageView, {
    _secondBgImageView.image = [UIImage imageNamed:@"img_guide_02_bg"];
    _secondBgImageView.contentMode = UIViewContentModeScaleToFill;
    _secondBgImageView.userInteractionEnabled = YES;
})
NWLazyPropertyWithInit(UILabel, secondTitleLabel, {
    _secondTitleLabel.text = @"权限设置";
    _secondTitleLabel.font = [UIFont nw_systemFontOfSize:24 weight:NWFontWeightMedium];
    _secondTitleLabel.textColor = [UIColor whiteColor];
    _secondTitleLabel.textAlignment = NSTextAlignmentCenter;
})
NWLazyPropertyWithInit(UILabel, secondSubTitleLabel, {
    _secondSubTitleLabel.text = @"仅用于安全相关功能，需全部开启以确保保护功能正常使用";
    _secondSubTitleLabel.font = [UIFont systemFontOfSize:13];
    _secondSubTitleLabel.textColor = [UIColor nw_colorWithHex:0xffffff alpha:.6f];
    _secondSubTitleLabel.textAlignment = NSTextAlignmentCenter;
    _secondSubTitleLabel.numberOfLines = 0.f;
})
- (NSArray<ISSafetyGuideAuthItemView *> *)authItemViews {
    if (!_authItemViews) {
        _authItemViews = [@[@0, @1, @2] bk_map:^id(id obj) {
            ISSafetyGuideAuthItemView *itemView = [[ISSafetyGuideAuthItemView alloc] init];
            return itemView;
        }];
    }
    return _authItemViews;
}
static BOOL hasClicked = NO;
NWLazyPropertyWithInit(UIButton, secondBtn, {
    _secondBtn.backgroundColor = [UIColor nw_colorWithHex:0x0078FF];
    [_secondBtn setTitle:@"一键申请权限" forState:UIControlStateNormal];
    _secondBtn.layer.cornerRadius = 6.f;
    _secondBtn.clipsToBounds = YES;
    @weakify(self)
    [_secondBtn bk_addEventHandler:^(id sender) {
        @strongify(self)
        if(hasClicked || [self.authItemViews bk_select:^BOOL(ISSafetyGuideAuthItemView *obj) {
            return obj.btn.enabled;
        }].count == 0) {
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            [self authAll];
            hasClicked = YES;
        }
    } forControlEvents:UIControlEventTouchUpInside];
})
NWLazyPropertyWithInit(UIButton, secondSkipBtn, {
    [_secondSkipBtn setTitle:@"暂时跳过" forState:UIControlStateNormal];
    [_secondSkipBtn setTitleColor:[UIColor nw_colorWithHex:0xFFFFFF alpha:0.4f] forState:UIControlStateNormal];
    _secondSkipBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    @weakify(self)
    [_secondSkipBtn bk_addEventHandler:^(id sender) {
        @strongify(self)
        [self dismissViewControllerAnimated:YES completion:nil];
    } forControlEvents:UIControlEventTouchUpInside];
})
@end
